<template>
    <div class="article-container">

        <el-row :gutter="20">
            <el-col :span="18">
                <div class="article-left-part">
                    <div class="article-content-box">
                        <div class="article-title">
                            <h1 v-text="article.title"></h1>
                        </div>
                        <div class="article-user-info">
                            <el-avatar :src="article.user.avatar" class="article-page-user-avatar"></el-avatar>
                            <span>
                            {{ article.user.userName }}
                        </span>
                        </div>
                        <div class="article-info">
                            <span class="el-icon-date" v-text="'发表于' + formatDate(article.createTime)"></span>
                            <span class="el-icon-view" v-text="'浏览量' + this.article.viewCount"></span>
                        </div>
                        <div class="article-labels">
                            <el-tag type="danger"
                                    v-for="(tag, tagIndex) in this.article.labels"
                                    :key="tagIndex">
                                <a :href="'/search?keyword=' + tag" target="_blank">{{ tag }}</a>
                            </el-tag>
                        </div>
                        <div class="article-content" id="article-content" v-html="this.article.content">

                        </div>
                    </div>

                    <div class="article-comment-box">
                        <div class="article-comment-tip">
                            评论列表
                        </div>
                        <div v-for="(item, index) in this.comments.content"
                             :key="index"
                             class="comment-item">
                            <div class="comment-user-info">
                                <a :href="'/user/' + item.userId">
                                    <el-avatar class="article-comment-user-avatar" :src="item.userAvatar"/>
                                </a>
                                <span style="margin-left: 5px">{{ item.userName }}</span>

                            </div>
                            <div v-if="item.parentContent !== ''" class="comment-replay">
                                <span>回复： {{ item.parentContent }}</span>
                            </div>
                            <div class="article-comment-content">
                                <el-tag type="danger" size="mini" v-if="item.state === '3'">置顶</el-tag>
                                {{ item.content }}
                            </div>
                            <div class="article-comment-action">
                                <span class="el-icon-date" v-text="formatDate(item.createTime)"></span>
                                <span class="article-comment-recall">回复</span>
                            </div>
                        </div>

                        <div v-if="pageNavigation.totalElements === 0"
                             class="no-comment-content">
                            暂时没有评论，赶快来评论吧！
                        </div>

                        <el-pagination
                            v-else
                            :current-page="pageNavigation.currentPage"
                            :page-size="pageNavigation.pageSize"
                            :page-sizes="[5]"
                            :total="pageNavigation.totalElements"
                            layout="total, sizes, prev, pager, next, jumper"
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange">
                        </el-pagination>

                        <div class="article-comment-input">
                            <el-input
                                @focus="checkLogin"
                                v-model="comment.content"
                                maxlength="100"
                                placeholder="写一个友善的评论"
                                resize="none"
                                rows="6"
                                show-word-limit
                                type="textarea">
                            </el-input>


                            <el-row :gutter="10" style="margin-top: 20px;">
                                <el-col :offset="21" :span="1">
                                    <el-button size="mini" type="primary" @click="doComment">评论</el-button>
                                </el-col>
                            </el-row>
                        </div>
                    </div>

                    <div class="recomment-article-box">
                        <div class="recomment-tip">
                            推荐文章
                        </div>

                        <div v-for="(item, index) in recommendArticle"
                             :key="index"
                             class="recomment-item">

                            <NuxtLink :to="'/article/' + (item.id)">
                                <h3 v-text="item.title"></h3>
                            </NuxtLink>

                            <div class="recomment-summary" v-text="item.summary">

                            </div>
                            <div class="recomment-info">
                                <span class="el-icon-date" v-text="'发表于' + formatDate(item.createTime)"></span>
                                <span class="el-icon-view" v-text="'浏览量' + item.viewCount"></span>

                                <el-tag v-for="(tag, tagIndex) in item.labels"
                                        :key="tagIndex"
                                        class="recomment-article-label"
                                        size="mini"
                                        type="danger">
                                    <a :href="'/search?keyword=' + tag" target="_blank">{{ tag }}</a>
                                </el-tag>
                            </div>

                        </div>
                    </div>
                </div>
            </el-col>
            <el-col :span="6">
                <div class="article-right-part">
                    <div class="right-card">
                        <div class="word-cloud-title">热门标签</div>
                        <div class="card-content">
                            <div class="labels-list-box">
                                <LRWordCloud style="height: 240px"/>
                            </div>
                        </div>
                    </div>
                    <div class="right-card">
                        <div class="word-cloud-title">广告</div>
                        <div class="taobao-ad-box">
                            <TaobaoLoop/>
                        </div>
                    </div>
                </div>
            </el-col>
        </el-row>

        <div class="dialog-part">
            <!--            显示图片的弹窗-->
            <el-dialog
                :before-close="handleClose"
                :close-on-click-modal="true"
                :close-on-press-escape="true"
                :fullscreen="false"
                :visible.sync="dialogVisible"
                title="原图"
                width="80%">
                <el-image :src="imageSrc" fit="fill"></el-image>
            </el-dialog>

            <el-dialog
                :before-close="handleClose"
                :close-on-click-modal="false"
                :close-on-press-escape="false"
                :visible.sync="jumpToLoginDialogVisible"
                title="提示"
                width="30%">
                <span>评论需要先登录,是否跳到登录界面？</span>
                <span slot="footer" class="dialog-footer">
                <el-button @click="jumpToLoginDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="jumpToLogin">确 定</el-button>
              </span>
            </el-dialog>

        </div>
    </div>
</template>

<script>
import {getArticleDetail, getRecommendArticleByArticleId} from "assets/api/article-portal-api";
import {success_code} from "assets/utils/LRConstant";
import {formatDate} from "assets/utils/date";
import highLight from 'highlight.js'
import 'highlight.js/styles/a11y-dark.css'
import TaobaoLoop from "@/components/TaobaoLoop";
import LRWordCloud from "@/components/LRWordCloud";
import {getOwnInfo} from "assets/api/userApi";
import {postComment, getCommentsByArticleId} from "assets/api/comment-portal-api";

export default {
    components: {LRWordCloud, TaobaoLoop},
    data() {
        return {
            imageSrc: '',
            dialogVisible: false,
            jumpToLoginDialogVisible: false,
            recommendArticle: [],
            pageNavigation: {
                currentPage: 1,
                totalPages: 1,
                pageSize: 5,
                totalElements: 10
            },
            article: {
                id: "767503493815599104",
                title: "冬天",
                userId: "730811351965892608",
                userAvatar: null,
                userName: "liaorun",
                categoryId: "764599831149674496",
                content: "",
                type: "1",
                state: "3",
                summary: "冬天有很多有趣的事情，你能想到那些",
                label: "winter-happy new year-snow",
                viewCount: 47,
                createTime: "",
                updateTime: "",
                cover: "",
                user: {
                    id: "",
                    userName: "",
                    roles: "",
                    avatar: "",
                    email: "",
                    sign: "秋天",
                    state: "1",
                    regIp: "",
                    loginIp: "",
                    createTime: "",
                    updateTime: ""
                },
                labels: [],
            },
            comments: {
                content: [],
                totalPages: 1,
                currentPage: 1,
                totalElements: 1,
                pageSize: 5,
                first: true,
                last: true
            },
            comment: {
                id: "",
                parentContent: "",
                articleId: "",
                content: "",
                userId: "",
                userAvatar: "",
                userName: "",
                state: "",
                createTime: "",
                updateTime: ""
            }
        }
    },
    methods: {
        initData() {
            if (this.$route.params.id != null) {
                getArticleDetail(this.$route.params.id).then((result) => {
                    if (result.code === success_code) {
                        this.article = result.data;
                        this.$message.success(result.message);
                    } else {
                        this.$message.error(result.message);
                    }
                })
            }
        },
        formatDate(date) {
            return formatDate(new Date(date), "yyyy-MM-dd hh:mm");
        },
        showImage(event) {
            this.dialogVisible = true;
            this.imageSrc = event.target.src;
        },
        handleClose(done) {
            done();
        },
        toSearchPage: function () {
            // check data
            // 从字符串中删除前导和尾随的空格和行结束符字符
            this.keyword = this.keyword.trim();
            if (this.keyword === '') {
                return;
            }

            // change ui
            this.$router.push({
                path: '/search',
                query: {
                    keyword: encodeURIComponent(this.keyword),
                    page: 1,
                    size: 5,
                    categoryId: '',
                    sort: ''
                }
            });
            // location.href = "/search/" + encodeURIComponent(this.keyword);
        },
        handleCurrentChange(val) {
            this.pageNavigation.currentPage = val;
            this.getCommentsByArticleId();
        },
        handleSizeChange(value) {
            this.pageNavigation.pageSize = value;
            this.getCommentsByArticleId();
        },
        getCommentsByArticleId() {
            getCommentsByArticleId(this.$route.params.id, this.pageNavigation.currentPage, this.pageNavigation.pageSize).then((result) => {
                if (result.code === success_code) {
                    this.comments = result.data;

                    this.pageNavigation.currentPage = this.comments.currentPage;
                    this.pageNavigation.pageSize = this.comments.pageSize;
                    this.pageNavigation.totalElements = this.comments.totalElements;
                    this.pageNavigation.totalPages = this.comments.totalPages;
                }
            });
        },
        doComment() {
            // check env
            let myLoginCookie = document.cookie.indexOf("sob_blog_token");

            if (myLoginCookie === -1) {
                this.jumpToLoginDialogVisible = true;
                return;
            }
            if (this.comment.content.trim() === '') {
                this.$message.warning("评论不能为空");
                this.comment.content = '';
                return;
            }
            // complete submit data
            this.comment.articleId = this.article.id;
            // submit data
            postComment(this.comment).then((result) => {
                // check response data
                if (result.code === success_code) {
                    this.$message.success("评论成功");

                    // change data
                    this.comment.content = '';
                    this.getCommentsByArticleId();
                } else {
                    this.$message.error("评论失败 cause by:" + result.message);
                }
            })
        },
        checkLogin() {
            getOwnInfo().then((result) => {
                if (result.code !== success_code) {
                    this.jumpToLoginDialogVisible = true;
                }
            })
        },
        jumpToLogin() {
            this.jumpToLoginDialogVisible = false;
            location.href = '/login?redirect=' + location.href;
        }
    },
    mounted: function () {
        // init variable
        let articleContent = document.getElementById("article-content");
        let images = articleContent.querySelectorAll("img");

        this.pageNavigation.currentPage = this.comments.currentPage;
        this.pageNavigation.pageSize = this.comments.pageSize;
        this.pageNavigation.totalElements = this.comments.totalElements;
        this.pageNavigation.totalPages = this.comments.totalPages;

        // init Listener
        images.forEach((item) => {
            item.addEventListener('click', this.showImage)
        })
        // this.initData();
        // init ui
        highLight.initHighlighting();
    },
    async asyncData({params}) {
        let result = await getArticleDetail(params.id);
        let recommendArticle = await getRecommendArticleByArticleId(params.id, 5);
        let commentData = await getCommentsByArticleId(params.id, 1, 5);
        return {
            article: result.data,
            recommendArticle: recommendArticle.data,
            comments: commentData.data
        }
    },
}
</script>

<style>
.article-container {
    margin-top: 20px;
    margin-bottom: 20px;
}

.article-user-info {
    margin-top: 10px;
}

.article-page-user-avatar {
    vertical-align: middle;
}

.article-info {
    margin-top: 10px;
}

.article-label-item {
    margin-right: 5px;
}

.article-content {
    margin-top: 20px;
}

.article-content pre code {
    font-size: 14px;
    padding: 10px;
}

.article-content p {
    padding: 10px 0;
}

.article-content img {
    width: 100%;
    object-fit: cover;
    cursor: zoom-in;
}

.right-card {
    background-color: white;
    padding: 10px;
    font-size: 14px;
    margin-bottom: 10px;
    font-weight: 600;
}

.recomment-article-box, .article-content-box, .article-comment-box {
    margin-top: 20px;
    border-radius: 4px;
    padding: 20px;
    background-color: white;
}

.article-content-box {
    margin-top: 0px;
}


.recomment-item h3:hover {
    color: purple;
}

.recomment-item h3 {
    cursor: pointer;
}

.recomment-item {
    margin-top: 20px;
}

.recomment-tip, .article-comment-tip {
    color: blue;
    font-weight: 600;
}

.recomment-info span {
    margin-right: 5px;
}

.recomment-article-label:hover {
    background-color: orange;
    color: red;
}

.recomment-summary {
    margin: 5px 0;
    color: #909399;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 1;
    overflow: hidden;
}

.back-top {
    height: 100%;
    width: 100%;
    background-color: #f2f5f6;
    box-shadow: 0 0 6px rgba(0, 0, 0, .12);
    text-align: center;
    line-height: 40px;
    color: #1989fa;
}

.comment-user-info img {

}

.comment-user-info {
    margin-bottom: 10px;
}

.comment-item {
    padding: 10px 0;
    border-bottom: #f5f5f5 solid 1px;
}

.article-comment-action {
    color: gray;
    text-align: right;
}

.article-comment-content {
    padding: 10px;
    margin-left: 30px;
}

.article-comment-user-avatar {
    vertical-align: middle;
}

.no-comment-content {
    padding: 10px;
    text-align: center;
    cursor: pointer;
    margin-top: 20px;
}

.article-comment-input {
    margin-top: 20px;
}

.article-comment-recall:hover {
    color: purple;
}

.article-comment-recall {
    margin-left: 10px;
    cursor: pointer;
}
</style>